package xkp.lesson2;

import java.io.*;
import java.lang.reflect.Field;
import java.nio.Buffer;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.channels.FileChannel;

public class TestNIO {
    public static void main(String[] args) throws IOException {
        //1、NIO中Channel，操作文件
        //2、从通道中读取数据或者向通道中写数据需要Buffer参与
        //可以通过BIO的I/O流获取通道也可以直接通过文件获取通道
        FileInputStream inputStream = new FileInputStream("Lesson30/file/hosts");
        //获取通道
        FileChannel channel = inputStream.getChannel();
        //读取数据到Buffer中
        //buffer中有三个概念 容量Capiticy   limit:限制   posotion:位置
        ByteBuffer buffer = ByteBuffer.allocate(64);
/*        System.out.println("容量Capiticy:"+buffer.capacity());//64
        System.out.println("limit:限制:"+buffer.limit());//如果limit = capiticy-position
        System.out.println("posotion:位置:"+buffer.position());//position = 0*/
        //如果向buffer写数据  limit无效
        //limit在读取是有效
        int length = channel.read(buffer);
     /*   System.out.println(length);
        System.out.println("容量Capiticy:"+buffer.capacity());//64
        System.out.println("limit:限制:"+buffer.limit());//如果limit = capiticy-position
        System.out.println("posotion:位置:"+buffer.position());//position = 0*/
        //注意：postion在不断的变化
        while(length != -1){
            //写转换为读模式
            buffer.flip();//此处把position返回到0位置，才能开始读取  //1
            String str = new String(buffer.array(),0,length);
            System.out.print(str);
            //本次读取已经完成
            //下一次读取
            //清除上次数据
            buffer.clear(); //2
            //继续下一次读取
            length = channel.read(buffer);
        }

        channel.close();
    }

}
